# -*- coding: utf-8 -*
import json
import uuid

from flask import request, jsonify

from conf.flask_ini import FlaskIni
from conf.my_log import MyLog
from conf.redis_cnx import RedisCnxPool
from qa_diagnosis.simplediagnosis import Diagnosis, get_top_k
from simple_nlg import get_inquiry_record
from web.const import StatusCode
from web.const import CONTEXT

app = FlaskIni().get_app()
rbac = FlaskIni().get_rbac()
diagnosis_app = Diagnosis()
redis_conn = RedisCnxPool().get_conn()

logger = MyLog().get_logger()

prefix = f'{CONTEXT}/qa'


@app.route(f'{prefix}/diagnosis', methods=['POST'])
@rbac.allow(roles=['anonymous'], methods=['POST'])
def diagnosis():
    try:
        conversation_id = request.json['conversation_id']
        user_utterance = request.json['user_utterance']

        if user_utterance in ['你好', 'hello', 'hi', '您好']:
            return jsonify({'status': StatusCode.SUCCESS_CODE, 'message': '', 'payload': {
                'conversation_id': conversation_id,
                'question': 'Hi~，你好啊！'
            }})
        elif user_utterance in ['有', '是', '有的']:
            user_intent = 'YES'
        elif user_utterance in ['没', '没有', '没有了', '不是']:
            user_intent = 'DENY'
        else:
            user_intent = 'UNDEFINED'

        if not conversation_id:
            conversation_id = f'CDSS-QA-{str(uuid.uuid4())}'
            inquiry_list = [[user_utterance, None, '是']]
            diagnosis_app.entrance(disease_name_list=None,
                                   disease_freq_list=None,
                                   detailed_disease_list=None,
                                   inquiry_list=inquiry_list)
        else:
            value = str(redis_conn.get(name=conversation_id), encoding='utf-8')
            json_value = json.loads(value)

            disease_name_list = json_value['disease_name_list']
            disease_freq_list = json_value['disease_freq_list']
            detailed_disease_list = json_value['detailed_disease_list']
            inquiry_list = json_value['inquiry_list']
            max_likelihood_symptom = json_value['max_likelihood_symptom']
            max_likelihood_property = json_value['max_likelihood_property']

            inquiry_list.append([max_likelihood_symptom,
                                 max_likelihood_property,
                                 user_utterance])

            if len(detailed_disease_list) == 0:
                if user_intent == 'YES':
                    return jsonify({'status': StatusCode.SUCCESS_CODE, 'message': '',
                                    'payload': {
                                        'conversation_id': conversation_id,
                                        'question': '好的，请您输入您的症状。',
                                        'option_list': ''
                                    }})
                elif user_intent == 'DENY':
                    return jsonify({'status': StatusCode.SUCCESS_CODE,
                                    'message': '',
                                    'payload':
                                        {
                                            'inquiry_record': get_inquiry_record(inquiry_list),
                                            'top_k': get_top_k(disease_name_list, disease_freq_list)
                                        }
                                    })
                else:
                    inquiry_list = inquiry_list[:-1]
                    inquiry_list.append([user_utterance, None, '是'])

            logger.info(disease_name_list)
            logger.info(disease_freq_list)
            logger.info(detailed_disease_list)
            logger.info(inquiry_list)

            diagnosis_app.entrance(disease_name_list=disease_name_list,
                                   disease_freq_list=disease_freq_list,
                                   detailed_disease_list=detailed_disease_list,
                                   inquiry_list=inquiry_list)
        json_value = {
            'disease_name_list': diagnosis_app.disease_name_list,
            'disease_freq_list': diagnosis_app.disease_freq_list,
            'detailed_disease_list': diagnosis_app.detailed_disease_list,
            'inquiry_list': diagnosis_app.inquiry_list,
            'max_likelihood_symptom': diagnosis_app.max_likelihood_symptom,
            'max_likelihood_property': diagnosis_app.max_likelihood_property
        }
        # expire time is 2h
        redis_conn.set(name=conversation_id,
                       value=json.dumps(json_value, ensure_ascii=False),
                       ex=7200)
        payload = {
            'conversation_id': conversation_id,
            'question': diagnosis_app.question,
            'option_list': diagnosis_app.max_likelihood_option_list
        }
        return jsonify({'status': StatusCode.SUCCESS_CODE, 'message': '', 'payload': payload})
    except:
        raise EnvironmentError
